package cn.tedu.ticket;/**
 * @Author 金帮嘉诚 @Date 2021-06-23 星期三 11:17
 */
/*本类用于测试*/

/**
 * 知识点
 */
public class TestExtendsV2 {
    public static void main(String[] args) {
        TicketThreadV2_2 m4 = new TicketThreadV2_2("线程1");
        TicketThreadV2_2 m41 = new TicketThreadV2_2("线程2");
        TicketThreadV2_2 m42 = new TicketThreadV2_2("线程3");
        TicketThreadV2_2 m43 = new TicketThreadV2_2("线程4");

        m4.start();
        m41.start();
        m42.start();
        m43.start();
    }
}

class TicketThreadV2_2 extends Thread {
    static int ticketNumber = 100;

    public TicketThreadV2_2() {
    }

    public TicketThreadV2_2(String name) {
        super(name);
    }

        Object obj=new Object();//不行
    @Override
    public void run() {
        while (true) {

            //使用继承的方式，锁对象必须用 .class，
//            synchronized(this){用this不行，
//            synchronized(obj){用Object对象不行
            synchronized (TicketThreadV2_2.class) {
                if (ticketNumber > 0) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(this.getName() + "还剩" + ticketNumber-- + "张票，售出一张");
                }
                if (ticketNumber <= 0) {
                    System.out.println("抱歉！票已售完!");
                    break;
                }
            }
        }

    }
}
